<template>
  <div class="gallery" id="gallery" :class="{'noData': data.length === 0}" ref="content" >  
    <el-form class="gallery_detail"  :rules="rules" ref="form_detail" :model="curImage">
      <p ref="detail_title">图片详情</p> 
      <div :style="'height: ' + detailH +'px' ">
        <div class="gallery_item_detail" :style="'height: ' + (detailH -96) +'px' " >
          <el-image :src="utils.setCdnUrl() + curImage.url" v-if="curImage.url"></el-image>
          <div class="el-image" v-else></div>
          <p class="gallery_item_image">图片名称</p>
          <el-form-item prop="filename">
            <el-input type="textarea"  v-model="curImage.filename" :maxlength="25" :rows="2" resize="none"></el-input> 
          </el-form-item>
          <div class="gallery_detail_params">
            <p>尺寸</p>
            <p v-if="curImage.imagewidth">{{curImage.imagewidth}}×{{curImage.imageheight}}</p>
          </div>
          <div class="gallery_detail_params">
            <p>图片格式</p>
            <p v-if="curImage.imagewidth">{{curImage.imagetype}}</p>
          </div>
          <div class="gallery_detail_params">
            <p>大小</p>
            <p v-if="curImage.filesize">{{curImage.filesize}}KB</p>
          </div>
          <div class="gallery_detail_params">
            <p>上传时间</p>
            <p >{{curImage.uploadtime}}</p>
          </div>
          <div class="gallery_detail_params">
            <p>上传人</p>
            <p>{{curImage.admin_name}}</p>
          </div>
          <div class="gallery_detail_params">
            <p>文件夹</p>
            <p>{{curImage.foldername}}</p>
          
          </div>
        </div>
        <div class="gallery_item_btn" ref="detail_btn" v-if="curImage.imagewidth">
          <el-button type="search" @click="closeSaveDialog">保存</el-button>
          <el-button type="del"  @click="delCurImage">删除</el-button>
        </div>
      </div>
    </el-form>
    <div class="gallery_content">
      <div class="gallery_guide" ref="header">
        <p class="gallery_btn"> 
          <i class="iconfont icon-arrow_left" @click="folderPrev()" :class="{'not_allow': !(curFolderIndex > 0) }"></i>
        </p>
        <p class="gallery_folder" id="gallery_folder">
          <span v-for="(item, index) in listFolder" :key="item.id" :class="{'active': curFolder.label == item.label }" @click="setFolder(item, index)">{{item.label}}</span>
        </p>
        <div class="gallery_folder_btn">
          <i class="iconfont icon-arrow_right" @click="folderNext()" :class="{'not_allow': !(curFolderIndex <  (listFolder.length - 1)) }" ></i>
          <i class="iconfont icon-path_normal not_allow"  v-show="(curFolder.label == '所有图片' || curFolder.label =='我的图片')"></i>

          <el-popover   placement="bottom" width="104" trigger="click" v-show="!(curFolder.label == '所有图片' || curFolder.label =='我的图片')"
          popper-class="gallery_folder_btn_edit"  >
            <p @click="closeFolderDialog('edit')" >编辑文件夹</p>
            <p @click="closeFolderDelDialog()">删除文件夹</p>
            <i class="iconfont icon-path_normal" slot="reference" ></i>
          </el-popover>
          <i class="iconfont icon-add_normal" @click="closeFolderDialog('add')"></i>
        </div>
      </div>
      <div class="gallery_form" ref="form">
        <el-form  class=" "  @submit.native.prevent>
          <el-input placeholder="图片名称"  v-model="form.filename.value "  @keyup.enter.native="getTableList"></el-input>
        </el-form>
        <div class="btnContainer" >
          <div>
            <el-button type="search"  @click="closeUploadDialog()" v-if="$_has('/customer/set_status')">上传图片</el-button>
         
            <el-button type="del" @click="sureCloseDialog('del')">删除</el-button>
            <el-button type="del" @click="closeExportDialog">导出</el-button>
          </div>
          <div>
            <el-button type="search" @click="getTableList" v-if="$_has('/customer/list')">查询</el-button>
            <el-button type="del" @click="resetForm">重置</el-button>
          </div>
        </div>
      </div>
      <div class="gallery_no_data" :style="'height: ' + height" v-if="data.length === 0">
        <svg class="gallery_no_data_svg" >
          <use xlink:href="#icon-null_image"></use>
        </svg>
        <p>暂未上传任何照片</p>
      </div>
      <div class="gallery_data" v-loading="loading" :style="'height: ' + height" v-else>
        <div v-for="item in data" :key="item.url" class="gallery_data_item" @click="setImage(item)">
          <el-image :src="utils.setCdnUrl() +item.url" :class="{'active':curImage.url == item.url}"></el-image>
          <el-checkbox v-model="item.checked" @click.stop.native  @change="(value) => changeStatus(value, item)"></el-checkbox>
          <p>{{item.filename}}</p>
        </div>
     
      </div>
     
    </div>
    <Upload ref="upload" v-show="uploadShow" :show="uploadShow" @closeDialog="closeUploadDialog"></Upload>
    <Del v-show="delShow"  :show="delShow" @closeDialog="closeDelDialog"></Del>
    <Export v-show="exportShow" :show="exportShow" @closeDialog="closeExportDialog"></Export>
    <Folder ref="folder" v-show="folderShow" :show="folderShow" @closeDialog="closeFolderDialog"></Folder>
    <DelFolder v-show="delFolderShow" :show="delFolderShow" @closeDialog="closeFolderDelDialog"></DelFolder>
    <Save v-show="saveShow" :show="saveShow" @closeDialog="closeSaveDialog"></Save>
  </div>
</template>

<script>
import { Upload, Export, Del, Folder, DelFolder, Save } from './components'
import { galleryList, folderList } from '@/api/gallery/gallery.js'
import { setSearchParams, timeFormat } from '@/utils/index.js'
import { mapGetters } from 'vuex'
export default {
  name: 'gallery',
  data(){
    return {
      uploadShow: false,
      delShow: false,
      exportShow: false,
      folderShow: false, 
      delFolderShow: false,
      saveShow: false,
      detailH: '',
      height_detail: '',
      height: '',
      curList: [],
      form: {
        filename: { value: '', op: 'like' },
        is_history : { value: '0', op: '=' },
      },
      rules: {
        filename: [
          {  max: 24,message: '字段图片名称最多24字符！ ', trigger: 'change' }  
        ]
      },
      listFolder: [
        {label: '所有图片', id: '1'},
        {label: '我的图片', id: '2'},
      ],
      data: [],
      curFolder: {},
      // curFolder: {label: '所有图片', id: '1'},
      curImage: {},
      curSelect: [],
      pageSize: 18,
      page: 1,
      loading:  true,
      isDataReset : true,
      isDelCurImage: false,
      curFolderIndex: 0
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  components: { Upload, Export, Del,Folder, DelFolder, Save },
  mounted(){
    let that = this;
    that.setTableHeight()
    that.setDetailight()
    // 注：window.onresize只能在项目内触发1次
    window.onresize = function windowResize () {
        // 通过捕获系统的onresize事件触发我们需要执行的事件
      that.setTableHeight()
      that.setDetailight()
      if(that.uploadShow){
        that.$refs.upload.setDetailight()
      }
    }
  },
  created () {
    this.loading = true
    this.getFolderList()
  },
  methods: {
    folderPrev () {
      if (this.curFolderIndex > 0){
        for(let i = 0; i < this.listFolder.length; i++){
          if(i == this.curFolderIndex){
            this.curFolder = this.listFolder[i-1]
            this.curFolderIndex -= 1
            break
          }

        }
        this.selectFolder()
      }

    },
    folderNext () {
      let len = this.listFolder.length
      if (this.curFolderIndex < len){
        for(let i = 0; i < len -1; i++){
          if(i == this.curFolderIndex){
            this.curFolderIndex += 1
            this.curFolder = this.listFolder[this.curFolderIndex]
            break
           
          }
        }
        this.selectFolder()
      }
    },
    selectFolder () {
      this.$nextTick(() => {
        let activeObj = document.getElementById('gallery_folder').getElementsByClassName('active')[0]
        let selectMenu = document.getElementById('gallery_folder')
        let left = activeObj.offsetLeft - selectMenu.offsetLeft
        selectMenu.scrollTo({
          left: left,
          behavior: 'smooth'
        });
        this.getTableList()
      })
      
     
    },
  
    scrollEventListener () {
      this.$nextTick(() => {
        let galleryData = document.getElementsByClassName('gallery_data')[0]
        galleryData.onscroll = () => {
          let scrollTop = galleryData.scrollTop
          let scrollHeight = galleryData.scrollHeight;
          let offsetHeight  = galleryData.offsetHeight ;
          if ((offsetHeight + scrollTop) - scrollHeight >= -1 &&  !this.loading ) {
            //每次滚动到底部size+10
            this.loading = true
            this.page+=1
            this.getScrollTableList()
          }
        }
      })
    
      
    },
    changeStatus (value, item){
      if(value){
        this.curSelect.push(item.id)
      }else{
        let index = this.curSelect.indexOf(item.id)
        if(index > -1){
          this.curSelect.splice(index, 1)
        }
      }
    },
    setFolder (item,i) {
      this.curFolder = item
      this.curFolderIndex = i
      this.getTableList()
    },
    setImage(item){
      let image = JSON.parse(JSON.stringify(item))
      image.filesize = parseInt(item.filesize / 1024)
      let date = new Date(item.uploadtime*1000)
      image.uploadtime = timeFormat(date)
      if(item.folder_id == 0){
        image.foldername = '所有图片'
      }else {
        let len = this.listFolder.length
        if(len > 0) {
          for(let i = 0; i < len; i++ ){
            if(this.listFolder[i].id == item.folder_id){
              image.foldername = this.listFolder[i].label
            }
          }
        }
      }
      this.curImage  = image
    },
    delCurImage () {
      this.curSelect = [this.curImage.id]
      this.isDelCurImage = true
      this.closeDelDialog()
    },
    getFolderList () {
      folderList().then(res => {
        if(res.state == 1){
           let array = [
            {label: '所有图片', id: '1'},
            {label: '我的图片', id: '2'},
          ]
          let list =  array.concat(res.data) 
          // 编辑的时候 当前选folder不变，删除的时候变为第一个
          let list_len_folder =  list.length
          if( this.curFolder){
            let len = list_len_folder
            for(let i = 0; i < list_len_folder; i++){
              if(this.curFolder.id !== list[i].id){
                len--
              }else {
                this.curFolder = list[i]
                this.curFolderIndex = i
              }
            }
            if(len == 0 ){
              this.curFolder = this.listFolder[0]
              this.curFolderIndex =  0
            }
          } else{
            this.curFolder = this.listFolder[0]
            this.curFolderIndex = 0
          }
          
          this.listFolder = list
          this.getTableList()
        }
      })
    },
    setParams (page) {
      this.loading = true
      let form = this.form
      if (this.curFolder.label == '我的图片'){
        form.admin_id = { value: this.userInfo.id, op: '=' }
        delete form.folder_id
      } else if (this.curFolder.label !== '所有图片') {
        form.folder_id = { value: this.curFolder.id, op: '=' }
        delete form.admin_id
      } else {
        if(form.folder_id){
          delete form.folder_id
        }
        if(form.admin_id){
          delete form.admin_id
        } 
      }
      let params = setSearchParams(form, this.pageSize, page, 'asc', 'uploadtime')
      return params
    },
    getScrollTableList () {
      let params = this.setParams(this.page)
      this.isDataReset && galleryList(params).then(res=>{
        let list = res.data.data
        // 判断是否可持续加载
        if( list.length == 0 && this.page > 1){
          this.isDataReset = false
        } else {
          this.isDataReset = true
        }
        for (let i = 0; i < list.length; i++){
          list[i].checked= false
        }
        if(this.data.length > 0 && this.page !== 1){
          this.data = this.data.concat(list)
        }else{
          this.data = list
        }
       
        this.page = res.data.current_page
        this.loading = false
      })
      if(!this.isDataReset) {
        this.loading = false
      }
     
    },
    getTableList(){
      let params = this.setParams(1)
      galleryList(params).then(res=>{
        let list = res.data.data
        this.data = list
        this.isDataReset = true
        this.page = res.data.current_page
        if(list.length > 0){
          this.setImage(list[0]) 
        } else {
          this.curImage = {
            filename: '',
            imageheight: '',
            imagetype: '',
            imagewidth: '',
            uploadtime: '',
            url: ''
          }
        }
        this.loading = false
        this.page == 1 && this.scrollEventListener()

        
      })
    },
    closeFolderDialog (type) {
      if(!this.folderShow){
        if(type === 'edit'){
          this.$refs.folder.isEdit = true
        }else{
          this.$refs.folder.isEdit = false
        }
      }

      this.folderShow = !this.folderShow
      if(!this.folderShow){
        this.getFolderList()
      }
    },
    closeFolderDelDialog () {
      this.delFolderShow = !this.delFolderShow
      if(!this.delFolderShow){
        this.getFolderList()
      }
    },
    closeSaveDialog () {
      this.$refs.form_detail.validate((valid)=>{
        if(valid) {
          this.saveShow = !this.saveShow
        }
      })
      if(!this.saveShow){
        this.page = 1
        this.getTableList()
      }
      
    },
    closeUploadDialog () {
      this.uploadShow = !this.uploadShow
      if(!this.uploadShow){
        this.page = 1
        this.getTableList()
      }
    },
    closeDelDialog (){
      this.delShow = !this.delShow
      if(!this.delShow){
        this.page = 1
        this.getTableList()
      }
    },
    closeExportDialog(){
      this.exportShow = !this.exportShow
    },
    sureCloseDialog(type){
      if(this.curSelect.length > 0){
        if(type == 'del'){
          this.isDelCurImage = false
          this.closeDelDialog()
        }
      } else {
        let word = "删除"
        this.$message.error('请选择需' + word + '的选项！')
      }
      
    },
    setTableHeight(){
      let searchFormH = this.$refs.form.offsetHeight;
      let manageMenuH = this.$refs.content.offsetHeight;
      let btnContainerH = this.$refs.header.offsetHeight;
      let tableHeight = manageMenuH  - btnContainerH - searchFormH - 24 - 24 - 24
      this.height = tableHeight +'px' 
    },
    setDetailight(){
      let manageMenuH = this.$refs.content.offsetHeight;
      let btnContainerH = this.$refs.detail_title.offsetHeight;
      let tableHeight = manageMenuH  - btnContainerH - 24 - 24 - 24 -24 - 6
      this.height_detail = tableHeight 
      this.setDetailH()
    },
    setDetailH (){
      // let detail_btnH = this.$refs.detail_btn.offsetHeight
      this.detailH =  this.height_detail + 24 + 6 + 24
    },
    resetForm(){
      for(let item in this.form){
        this.form[item].value =""
      }
      this.getTableList()
    }
  }

}
</script>


<style lang="scss">
@import '@/styles/gallery/gallery.scss';


</style>